JavaScript - save to file

revision:


Content

definition and usage ways to create/save files - examples function will save the textbox content to a file...


definition and usage

top

The possible ways to create and save files in Javascript are:

- use a library called "FileSaver": saveAs(new File(["CONTENT"], "demo.txt", {type: "text/plain;charset=utf-8"}));

- create a blob object and offer a "save as".

var a = document.createElement("a");
a.href = window.URL.createObjectURL(new Blob(["CONTENT"], {type: "text/plain"}));
a.download = "demo.txt";
a.click();

- upload the data, save it on the server.

var data = new FormData();
data.append("upfile", new Blob(["CONTENT"], {type: "text/plain"}));
fetch("SERVER.SCRIPT", { method: "POST", body: data });

- create a writable file stream.

const fileHandle = await window.showSaveFilePicker();
const fileStream = await fileHandle.createWritable();
await fileStream.write(new Blob(["CONTENT"], {type: "text/plain"})); await fileStream.close();

- in NodeJS, simply use the file system module: require("fs").writeFile("demo.txt", "Foo bar!");


ways to create/save files - examples

top

use "filesaver.js"

example: code
codes:
              <!-- (A) LOAD FILE SAVER -->
              <!-- https://cdnjs.com/libraries/FileSaver.js -->
              <!-- https://github.com/eligrey/FileSaver.js -->
              <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
              
              <script>
              // (B) "SAVE AS"
              var myFile = new File(["CONTENT"], "demo.txt", {type: "text/plain;charset=utf-8"});
              saveAs(myFile);
              </script>
          

create file from blob and force download

example: code
codes
            <script>
                // (A) CREATE BLOB OBJECT
                var myBlob = new Blob(["CONTENT"], {type: "text/plain"});
                
                // (B) CREATE DOWNLOAD LINK
                var url = window.URL.createObjectURL(myBlob);
                var anchor = document.createElement("a");
                anchor.href = url;
                anchor.download = "demo.txt";
                    
                // (C) "FORCE DOWNLOAD"
                // NOTE: MAY NOT ALWAYS WORK DUE TO BROWSER
                    SECURITY
                // BETTER TO LET USERS CLICK ON THEIR OWN
                anchor.click();
                window.URL.revokeObjectURL(url);
                document.removeChild(anchor);
            </script>
        

upload blob to server

example: code
codes
            <script>
                function blobajax () {
                // (A) CREATE BLOB OBJECT
                var myBlob = new Blob(["CONTENT"], {type: "text/plain"});
                
                // (B) FORM DATA
                var data = new FormData();
                data.append("upfile", myBlob);
                
                // (C) AJAX UPLOAD TO SERVER
                fetch("3b-upload.php", {
                    method: "POST",
                    body: data
                })
                .then((res) => { return res.text(); })
                .then((txt) => { console.log(txt); });
                }
                </script>
                <input type="button" value="Go" onclick="blobajax()"/>
                <?php
                echo move_uploaded_file(
                $_FILES["upfile"]["tmp_name"], 
                "demo.txt"
                ) ? "OK" : "ERROR UPLOADING";?>
        

writable file stream

example: code
codes
            <script>
                async function saveFile() {
                // (A) CREATE BLOB OBJECT
                var myBlob = new Blob(["CONTENT"], {type: "text/plain"});
                
                // (B) FILE HANDLER & FILE STREAM
                const fileHandle = await window.showSaveFilePicker({
                    types: [{
                    description: "Text file",
                    accept: {"text/plain": [".txt"]}
                    }]
                });
                const fileStream = await fileHandle.createWritable();
                
                // (C) WRITE FILE
                await fileStream.write(myBlob);
                await fileStream.close();
                }
                </script>
                
                <input type="button" value="Save File" onclick="saveFile()"/>
        

write to file in node.js

example: code
codes
            // (A) LOAD FILE SYSTEM MODULE
            // https://nodejs.org/api/fs.html
            const fs = require("fs");
            
            // (B) WRITE TO FILE
            fs.writeFile("demo.txt", "CONTENT", "utf8", (error, data) => {
            console.log("Write complete");
            console.log(error);
            console.log(data);
            });
            
            /* (C) READ FROM FILE
            fs.readFile("demo.txt", "utf8", (error, data) => {
            console.log("Read complete");
            console.log(error);
            console.log(data);
            });
            */
        

save files in JS, using an anchor element

example: code
codes
            <script>
                function createBlob(data) {
                    return new Blob([data], { type: "text/plain" });
                }
                function saveAs(content, fileName) {
                    const a = document.createElement("a");
                    const isBlob = content.toString().indexOf("Blob") > -1;
                    let url = content;
                    if (isBlob) {
                        url = window.URL.createObjectURL(content);
                    }
                    a.href = url;
                    a.download = fileName;
                    a.click();
                    if (isBlob) {
                        window.URL.revokeObjectURL(url);
                    }
                }
                // Consume the function as follows:
                const file = createBlob("Hello, file!");
                saveAs(file, "myFile.txt");
            </script>
        

save files in JS, using file-saver library

example: code
codes
            <script>
                const FileSaver = require('file-saver');
                // Save Blob file
                const file = createBlob('Hello, file!');
                FileSaver.saveAs(file, "myFile.txt");
                // Save URL
                FileSaver.saveAs("https://httpbin.org/image", "image.jpg");
            </script>
        


function will save the textbox content to a file...

top
example: function to save to file

Click button to save the text box in a file


codes:
                <div>
                    <input type=texarea id=mytext>
                    <br/>
                    <p>Click button to save the text box in a file</p>
                    <input type='button' onclick=saveFile() value='Save Text Box' /> 
                    <br/>
                </div>
                <style>
                    /* style table */
                    table {border-collapse: collapse;}
                    td {border: 1px gray solid; padding: 4px;  width: 5em;}
                </style>
                <script>
                    function saveFile(){  
                        // get the textbox data...
                        textToWrite = document.getElementById("mytext").value;
                        // put the data in a Blob object...
                        var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
                        // create a hyperlink <a> element tag that will be automatically clicked below...
                        var downloadLink = document.createElement("a");
                        // set the file name...
                        downloadLink.download = "fileName.txt";
                        // set the <a> tag href as a URL to point to the Blob
                        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
                        // automaitcally click the <a> element to go to the URL to save the 
                        textFileAsBlob...
                        downloadLink.click();
                    }
                </script>